﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using Microsoft.Win32;

namespace WeaverCustomTool
{
    [Guid("D391BF48-7E37-48D6-AD3E-7EE9C0622F22")]
    [ComVisible(true)]
    public partial class CustomTool : BaseCodeGeneratorWithSite
    {

        private static Guid CustomToolGuid = new Guid("{D391BF48-7E37-48D6-AD3E-7EE9C0622F22}");

        private static Guid CSharpCategory = new Guid("{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}");

        private static Guid VBCategory = new Guid("{164B10B9-B200-11D0-8C61-00A0C91E29D5}");

        private const string CustomToolName = "AopCustomTool";

        private const string CustomToolDescription = "Generate implementation from interface and aspects";

        private const string KeyFormat = @"SOFTWARE\Microsoft\VisualStudio\{0}\Generators\{1}\{2}";

        protected static void Register(Version vsVersion, Guid categoryGuid)
        {
            string subKey = String.Format(KeyFormat,
                                          vsVersion, categoryGuid.ToString("B"), CustomToolName);

            using (RegistryKey key = Registry.LocalMachine.CreateSubKey(subKey))
            {
                key.SetValue("", CustomToolDescription);
                key.SetValue("CLSID", CustomToolGuid.ToString("B"));
                key.SetValue("GeneratesDesignTimeSource", 1);
            }
        }

        protected static void Unregister(Version vsVersion, Guid categoryGuid)
        {
            string subKey = String.Format(KeyFormat,
                                          vsVersion, categoryGuid.ToString("B"), CustomToolName);

            Registry.LocalMachine.DeleteSubKey(subKey, false);
        }

        [ComRegisterFunction]
        public static void RegisterClass(Type t)
        {
            // Register for both VS.NET 2002 & 2003 (C#) 
            Register(new Version(11, 0), CSharpCategory);
            Register(new Version(11, 0), VBCategory);
        }

        [ComUnregisterFunction]
        public static void UnregisterClass(Type t)
        {
            Unregister(new Version(11, 0), CSharpCategory);
            Unregister(new Version(11, 0), VBCategory);
        }
    }
}
